package com.xxxx.server;

import com.alibaba.fastjson.JSON;
import com.xxxx.server.exceptions.ParamsException;
import com.xxxx.server.pojo.RespBean;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @Author 乔通
 * @Date 2020/10/17 16:55
 * Created by IntelliJ IDEA 2020.1.
 * Project: yeb
 * Description： 全局异常捕获。可以捕获异常，并将异常信息传送到前端。前端页面会弹出自定义异常信息。配合AssertUtil使用
 *
 */

@Component
public class GlobalExceptionHandler implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest req, HttpServletResponse resp, Object o, Exception e) {

                //返回JSON
                RespBean respBean = new RespBean();
                respBean.setCode(500);
                respBean.setMessage("服务器开了小差，请刷新后再试");
                //如果是自定义异常
                if (e instanceof ParamsException){
                    ParamsException ex =(ParamsException) e;
                    respBean.setCode(500);
                    respBean.setMessage(ex.getMsg());
                }
                // 设置响应类型和编码格式 （响应JSON格式）
                resp.setContentType("application/json;charset=utf-8");
                //得到输出流
                PrintWriter out=null;
                try {
                    out=resp.getWriter();
                    // 将对象转换成JSON格式，通过输出流输出
                    out.write(JSON.toJSONString(respBean));
                    out.flush();
                }catch (Exception e1){
                    e1.printStackTrace();
                }finally {
                    if (out!=null){
                        out.close();
                    }
                }
                return null;
            }
}
